<template>
  <div class="all-infomation">
    <div class="login-container">
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        auto-complete="on"
        label-position="left"
      >

        <div class="title-container">
          <h3 class="title">党员微积分后台管理系统</h3>
        </div>

        <el-form-item prop="userId">
          <span class="svg-container">
            <svg-icon icon-class="user" />
          </span>
          <el-input
            ref="userId"
            v-model="loginForm.userId"
            placeholder="请输入用户名"
            name="userId"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>

        <el-form-item prop="userPwd">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="userPwd"
            v-model="loginForm.userPwd"
            :type="passwordType"
            placeholder="请输入密码"
            name="userPwd"
            tabindex="2"
            auto-complete="on"
            @keyup.enter.native="handleLogin"
          />
          <span
            class="show-pwd"
            @click="showPwd"
          >
            <svg-icon :icon-class="passwordType === 'userPwd' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>

        <el-button
          :loading="loading"
          type="primary"
          style="width:100%;margin-bottom:30px;"
          @click.native.prevent="handleLogin"
        >登录</el-button>

      </el-form>
    </div>
    <!-- 全部提示信息 -->
    <div>
      <el-dialog
        title="请选择您要登录的管理系统"
        :visible.sync="showSelectUserType"
        center
        width="380px"
      >
        <el-row>
          <el-col :span="8">
            <p class="select-title">请选择权限</p>
          </el-col>
          <el-col :span="16">
            <el-select v-model="jurisdictionId" placeholder="请选择" class="select-jurisdiction">
              <el-option
                v-for="item in userTypeName"
                :key="item.jurisdictionId"
                :label="item.jurisdictionName"
                :value="item.jurisdictionId"
              />
            </el-select>
          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isShowSelectUserAllType(0)">取 消</el-button>
          <el-button type="primary" @click="isShowSelectUserAllType(1)">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>

</template>

<script>
import store from '../../store'
import { getRouterByUserType } from '../../api/user.js'
import { getJurisdictionName } from '../../api/jurisdiction.js'
import { findNowSemester } from '../../api/semester.js'
export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('输入密码不要短于4位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        userId: '',
        userPwd: ''
      },
      loginRules: {
        userId: [{ required: true, trigger: 'blur', validator: validateUsername }],
        userPwd: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false,
      passwordType: 'userPwd',
      redirect: undefined,
      userTypeName: [],
      showSelectUserType: false,
      jurisdictionId: '',
      // 路由名字
      flist: [],
      slist: [],
      tlist: [],
      allList: []
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.userPwd.focus()
      })
    },
    handleLogin() {
      var that = this
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then((res) => {
            const userAllType = store.getters.token
            const loginmsg = store.getters.loginmsg
            if (loginmsg !== '操作成功') {
              that.$message({
                message: loginmsg,
                type: 'error'
              })
              that.$store.dispatch('user/resetToken')
            } else {
              // 分割userType，判断是否存在多权限问题
              const userType = userAllType.split(',')
              var userStatus = sessionStorage.getItem('userStatus')
              if (userStatus === '0' || userStatus === 0) {
                that.$message({
                  message: '当前用户处于封禁状态',
                  type: 'error'
                })
                that.$store.dispatch('user/resetToken')
              } else {
                // 判断是否存在多权限问题
                if (userType.length === 1) {
                  if (userType[0] === '8' || userType[0] === 8) {
                    that.$message({
                      message: '该用户无登录权限',
                      type: 'error'
                    })
                    that.$store.dispatch('user/resetToken')
                  } else {
                    that.getSemester(userType[0])
                  }
                } else {
                  // 多权限，进行条件选择
                  that.selectUserType(userType)
                }
              }
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    },

    // 选择用户权限的方法
    selectUserType(userType) {
      var that = this
      const userTypeName = []
      // 之后根据用户权限获取对应名称
      for (var y = 0; y < userType.length; y++) {
        if (userType[y] === '8') {
          userType.splice(y, 1)
          break
        }
      }
      for (var x = 0; x < userType.length; x++) {
        getJurisdictionName(userType[x]).then((data) => {
          // 只存非个人权限
          if (data.obj.jurisdictionId !== '8') {
            userTypeName.push(data.obj)
          }
        })
      }
      that.userTypeName = userTypeName
      // 去掉个人权限外，判断是否只有一个权限
      if (userType.length === 1) {
        that.getSemester(userType[0])
      } else {
        that.showSelectUserType = true
      }
    },

    // 用户权限选择框是否显示的方法
    isShowSelectUserAllType(id) {
      var that = this
      if (id === 0) {
        this.showSelectUserType = false
        that.$store.dispatch('user/resetToken')
      } else if (id === 1) {
        // 获取当前学期的全部信息
        that.getSemester(that.jurisdictionId)
        this.showSelectUserType = false
      }
    },
    // 获取当前学期的全部信息
    getSemester(user_type) {
      var that = this
      new Promise(function(resolve, reject) {
        findNowSemester().then(res => {
          if (res.obj === null) {
            // 判断是否为支部数据或超级管理员登陆
            if (user_type === '0' || user_type === '1') {
              sessionStorage.setItem('semId', '无开放学期')
              resolve()
            } else {
              that.$message({
                message: '当前无开放学期，无法登陆',
                type: 'error'
              })
            }
          } else {
            const semId = res.obj.semId
            sessionStorage.setItem('semId', semId)
            sessionStorage.setItem('semCheckStartTime', res.obj.semCheckStartTime)
            sessionStorage.setItem('semCheckStopTime', res.obj.semCheckStopTime)
            resolve()
          }
        })
      }).then(() => {
        // 根据当前权限获取路由信息
        this.savingRouter(user_type)
      })
    },
    // 根据当前权限获取路由信息
    savingRouter(userType) {
      getRouterByUserType(userType).then((res) => {
        // 保存当前动态路由到session中
        store.commit('SET_USER_ROUTER_TYPE', res.obj)
        sessionStorage.setItem('userRouterType', JSON.stringify(res.obj))
        // 准备登录
        this.savingUserInfo(userType)
      })
    },
    // 准备登录
    savingUserInfo(user_type) {
      var that = this
      var user_Type = user_type
      sessionStorage.setItem('user_Type', user_Type)
      if (sessionStorage.getItem('userTypeName') !== null) {
        sessionStorage.removeItem('userTypeName')
      }
      that.$router.push({ path: that.redirect || '/' })
    }

  }

}

</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.all-infomation{
  background-color: #2d3a4b;
  height: 100%;
}
.login-container {

  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .select-title{
    margin-bottom: 30px;
  }
  .select-jurisdiction{
    width: 250px;
  }
}
</style>
